package br.ufmg.ubicomp.droidguide.application;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import br.ufmg.ubicomp.droidguide.R;
import br.ufmg.ubicomp.droidguide.common.DroidGuideConfigurationManager;
import br.ufmg.ubicomp.droidguide.common.DroidGuideConstants;
import br.ufmg.ubicomp.droidguide.eventservice.notification.DGNotificationType;
import br.ufmg.ubicomp.droidguide.scheduler.DroidGuideActivity;
import br.ufmg.ubicomp.droidguide.scheduler.SchedulerService;
import br.ufmg.ubicomp.droidguide.utils.AndroidUtils;



public abstract class ListActivities extends ListActivity {
	
	List<String> infoItems = new ArrayList<String>();
	List<String> infoKeys = new ArrayList<String>();
	List<Integer> infoItemColors = new ArrayList<Integer>();
	List<Boolean> infoItemsSubscribed = new ArrayList<Boolean>();
	List<DroidGuideActivity> activitiesToSubscribe = new ArrayList<DroidGuideActivity>();
	List<DroidGuideActivity> activitiesToUnSubscribe = new ArrayList<DroidGuideActivity>();
	private static final int COLOR_OFF = Color.BLACK;
	private static final int COLOR_ON = Color.RED;
			
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.info);
        initTouristActivities();
        
		int i = 0;
		for (String s: infoItems)
		{
			infoItemColors.add(COLOR_OFF);
			infoItemsSubscribed.add(Boolean.FALSE);
			i++;
		}
        
        // Use an existing ListAdapter that will map an array
        // of strings to TextViews
        setListAdapter(new ArrayAdapter<String>(this,
        		android.R.layout.simple_expandable_list_item_1, 
        		infoItems));
        
        getListView().setItemsCanFocus(true);
        getListView().setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View view, int arg2,
					long id) {
				String info = getItem((int)id);
				//showAlert(id, info);
				//showInfoView(info);
				handleMarkedItem(id);
			}
        	
        });
        
        getListView().setTextFilterEnabled(true);
	}
	
	private void handleMarkedItem(long id)
	{
		String service = infoItems.get((int) id);
		System.out.println(getListView().getChildCount());
		if (infoItemColors.get((int) id) == COLOR_ON){
			setBackgroundColorOfChild(id, COLOR_OFF);
			AndroidUtils.showAlert(this, "service " + service + " unmarked");
			AndroidUtils.showNotification(this, "Services", service + " removed from favorites.", DGNotificationType.OUTGOING, "Services");
		} else 
		{
			setBackgroundColorOfChild(id, COLOR_ON);
			AndroidUtils.showAlert(this, "service " + service + " marked");
			AndroidUtils.showNotification(this, "Services", service + " added to favorites.", DGNotificationType.OUTGOING, "Services");
		} 
	}
	
	private void setBackgroundColorOfChild(long id, int color) {
		View child = getListView().getChildAt((int) id);
		child.setBackgroundColor(color);
		infoItemColors.set((int) id, color);
	}
	
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

       menu.add(0,0, 0, "Ok").setIcon(R.drawable.ic_ok)
		 .setIntent(new Intent(android.provider.Settings.ACTION_SETTINGS));
       menu.add(0,1, 0, "Refresh").setIcon(R.drawable.ic_refresh)
		 .setIntent(new Intent(android.provider.Settings.ACTION_SETTINGS));
       menu.add(0,1, 0, "Cancel").setIcon(R.drawable.ic_cancel)
		 .setIntent(new Intent(android.provider.Settings.ACTION_SETTINGS));
      return true;
    }
	
	
	private String getItem(int id)
	{
		return infoItems.get(id);
	}
	
	protected void initTouristActivities()
	{
		SchedulerService service = SchedulerService.getInstance();
		String dgKey = DroidGuideConfigurationManager.getInstance().getData(
				DroidGuideConstants.DROID_GUIDE_USER_KEY);
		
		try {
			Collection<DroidGuideActivity> activities = 
				service.listActivities(dgKey);
			
			for (DroidGuideActivity act:activities)
			{
				infoItems.add(act.getName());
				infoKeys.add(act.getUserActivityKey());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			AndroidUtils.notifyError(e, this, "listActivities");
		}
		
//		infoItems.add("Pampulha Lake");
//		infoItems.add("Saint Francis Church");
//		infoItems.add("Pampulha Zoo");
//		infoItems.add("Ecological Park");
//		infoItems.add("Mineirao Stadium");
//		infoItems.add("Mineirinho Stadium");
//		infoItems.add("Museum of Art");
//		infoItems.add("Yatch club");
//		infoItems.add("Zoo Botanic Foundation");
//		infoItems.add("Federal University of Minas Gerais");
//		infoItems.add("Xapuri Restaurant");
//		infoItems.add("Pampulha Amusement Park");		
	}

	private void listActivities()
	{
		SchedulerService service = SchedulerService.getInstance();
		String dgKey = DroidGuideConfigurationManager.getInstance().getData(
				DroidGuideConstants.DROID_GUIDE_USER_KEY);
		
		try {
			Collection<DroidGuideActivity> activities = 
				service.listActivities(dgKey);
			
			for (DroidGuideActivity act:activities)
			{
				infoItems.add(act.getName());
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
//		infoItems.add("Pampulha Lake");
//		infoItems.add("Saint Francis Church");
//		infoItems.add("Pampulha Zoo");
//		infoItems.add("Ecological Park");
//		infoItems.add("Mineirao Stadium");
//		infoItems.add("Mineirinho Stadium");
//		infoItems.add("Museum of Art");
//		infoItems.add("Yatch club");
//		infoItems.add("Zoo Botanic Foundation");
//		infoItems.add("Federal University of Minas Gerais");
//		infoItems.add("Xapuri Restaurant");
//		infoItems.add("Pampulha Amusement Park");		
	}
	
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	Intent i;
    	int numSubActivities = 0;
    	int numUnsubActivities = 0;
    	if (item.getItemId() == 0) // OK
    	{
    		// subscribe to services
    		Collection<String> servicesToSubscribe = new ArrayList<String>();
    		Collection<String> servicesToUnsubscribe = new ArrayList<String>();
    		try {
				String dgKey = DroidGuideConfigurationManager.getInstance().getData(
						DroidGuideConstants.DROID_GUIDE_USER_KEY);

				for (int j = 0; j < infoItemColors.size(); j++)
				{
					int color = infoItemColors.get(j);
					// if the service has been selected
					if (color == COLOR_ON && !infoItemsSubscribed.get(j))
					{
						servicesToSubscribe.add(infoKeys.get(j));
					} else if (color == COLOR_OFF && infoItemsSubscribed.get(j))
					{
						servicesToUnsubscribe.add(infoKeys.get(j));
					}
				}
				
				SchedulerService service = SchedulerService.getInstance();
				
				numSubActivities = service.subscribeToActivities(activitiesToSubscribe, dgKey);
				
				numUnsubActivities = service.unsubscribeToActivities(activitiesToUnSubscribe, dgKey);
				
				Log.i("ListActivities", "subscribed activities: " + numSubActivities);
				Log.i("ListActivities", "unsubscribed activities: " + numUnsubActivities);
				
				if (numSubActivities > 0)
				{
					AndroidUtils.showNotification(this, "Services", "Subscription to "+numSubActivities+" services successful.", DGNotificationType.INCOMMING, "Subscription");
				}
				if (numUnsubActivities > 0)
				{
					AndroidUtils.showNotification(this, "Services", "Unsubscription to "+numUnsubActivities+" services successful.", DGNotificationType.INCOMMING, "Unsubscription");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				AndroidUtils.notifyError(e, this, "SubscribeToServices");
			}
    	} else if (item.getItemId() == 1) // refresh
    	{
            //updateItemColorsBasedOnSelection();		
    	}
    	if (item.getItemId() == 0 || item.getItemId() == 2)
    	{
    		finish();
    	}
    	
        return true;
		
	}
}
